'use strict';
define(['angular','jquery'],function(angular,$){
	
	/*
	创建自定义AngularJS 指令
	//创建指令模块 (或者检索现有模块) 
	var m = angular.module("myApp");
	
	// 创建"my-dir"指令 
	myApp.directive("myDir", function() { 
	  return { 
	    restrict: "E",        // 指令是一个元素 (并非属性) 
	    scope: {              // 设置指令对于的scope 
	      name: "@",          // name 值传递 （字符串，单向绑定） 
	      amount: "=",        // amount 引用传递（双向绑定） 
	      save: "&"           // 保存操作 
	    }, 
	    template:             // 替换HTML (使用scope中的变量) 
	      "<div>" + 
	      "  {{name}}: <input ng-model='amount' />" + 
	      "  <button ng-click='save()'>Save</button>" + 
	      "</div>", 
	    replace: true,        // 使用模板替换原始标记 
	    transclude: false,    // 不复制原始HTML内容 
	    controller: [ "$scope", function ($scope, $element, $attrs, $transclude) { …  }], 
	    compile: function(tElement, tAttrs, transclude) {  
   　　　　return {  
   　　　　　　pre: function preLink(scope, iElement, iAttrs, controller) { ... },  
   　　　　　　post: function postLink(scope, iElement, iAttrs, controller) { ... }  
   　　　　}  
   　　}, 
	    link: function (scope, element, attrs, controller) {…} 
	  } 
	});
	*/
	/*
	如果不使用^前缀，指令只会在自身的元素上查找控制器。指令定义只会查找定义在指令作当前用域中的ng-model=""
	如果使用?前缀,在当前指令中没有找到所需要的控制器，会将null作为传给link函数的第四个参数。
	如果添加了^前缀，指令会在上游的指令链中查找require参数所指定的控制器。
	如果添加了?^ 将前面两个选项的行为组合起来，我们可选择地加载需要的指令并在父指令链中进行查找
	如果没有任何前缀，指令将会在自身所提供的控制器中进行查找，如果没有找到任何控制器（或具有指定名字的指令）就抛出一个错误
	*/

	angular.module('app.treeView', [])
	.controller("treeViewController", ['$http',function($http){
		var vm = this;
	    /*
	      vm.tree = [
			   {
			      "id":"1",
			      "pid":"0",
			      "name":"家用电器",
			      "rows":[
			         {
			            "id":"4",
			            "pid":"1",
			            "name":"大家电",
			            "rows":[
			               {
			                  "id":"7",
			                  "pid":"4",
			                  "name":"空调",
			                  "chindren":[
			                     {
			                        "id":"15",
			                        "pid":"7",
			                        "name":"海尔空调"
			                     },
			                     {
			                        "id":"16",
			                        "pid":"7",
			                        "name":"美的空调"
			                     }
			                  ]
			               },
			               {
			                  "id":"8",
			                  "pid":"4",
			                  "name":"冰箱"
			               },
			               {
			                  "id":"9",
			                  "pid":"4",
			                  "name":"洗衣机"
			               },
			               {
			                  "id":"10",
			                  "pid":"4",
			                  "name":"热水器"
			               }
			            ]
			         },
			         {
			            "id":"5",
			            "pid":"1",
			            "name":"生活电器",
			            "rows":[
			               {
			                  "id":"19",
			                  "pid":"5",
			                  "name":"加湿器"
			               },
			               {
			                  "id":"20",
			                  "pid":"5",
			                  "name":"电熨斗"
			               }
			            ]
			         }
			      ]
			   },
			   {
			      "id":"2",
			      "pid":"0",
			      "name":"服饰",
			      "rows":[
			         {
			            "id":"13",
			            "pid":"2",
			            "name":"男装"
			         },
			         {
			            "id":"14",
			            "pid":"2",
			            "name":"女装"
			         }
			      ]
			   },
			   {
			      "id":"3",
			      "pid":"0",
			      "name":"化妆",
			      "rows":[
			         {
			            "id":"11",
			            "pid":"3",
			            "name":"面部护理"
			         },
			         {
			            "id":"12",
			            "pid":"3",
			            "name":"口腔护理"
			         }
			      ]
			   }
			];
				
		vm.itemClicked = function ($item) {
			vm.selectedItem = $item;
		};
		
		vm.itemCheckedChanged = function($item){
			$http.post('/url', $item);
		};
		*/
		return vm;
    }])
	    
	 .directive('treeView',function(){
		 
		 return {
			  restrict: 'EA', // E = Element, A = Attribute, C = Class, M = Comment
//				  template: '<div>hello template</div>',
			  templateUrl: function(element, attrs) {
			      return attrs.templateUrl || 'js/_directives/treeView.html';
			  },
			  replace: false,
			  scope: {
				  treeData: '=',
//					  templateUrl: '=',
				  checkboxShow: '=',
				  badgeShow:'@',//true（全部显示）,nkLeaf（叶子节点显示）,noLeaf（非叶子节点显示）
				  badgeField:'@',
				  textField: '@',
				  valueField: '@',
				  parentField: '@',
				  levelField: '@',
				  kindField: '@',
				  iconExpression: '@',
//					  nodeSort: '@',
				  subHeight: '@', //用屏幕高度减去的高度
				  itemExpandToggle: '&',
				  onRowClicked: '&',
				  onRowDblClicked: '&',
				  itemCheckedToggle: '&'
			  },
			 controller:['$scope', function($scope){
//					 $scope.number = $scope.number + "22222 ";  
				 
				 this.name='我是指令中的控制器！';
				 
				 //已经直接写入模板中。。。
				 $scope.init = function(item){
					 //被循环调用，循环次数为rows.length
//							return item[$scope.kindField].value=='nkLeaf'; 
					 //row[parentField].value==null?row.$$isVisible=true:angular.noop
					 //由于是排序查询得到结果，所以rows中的第一行一定是根节点
//						 if($scope.treeData.rows.length>0){
						 //获取第一行（就是跟节点）的层次
//							 var rootLevel = $scope.treeData.rows[0][$scope.levelField].value;
//						 }
					 if(item[$scope.levelField].value == $scope.treeData.rows[0][$scope.levelField].value){
						 item.$$isVisible=true;
					 }else{
						 item.$$isVisible=false;
					 }
					 

				 };

				 $scope.isLeaf = function(item){
//						return item[$scope.kindField].value=='nkLeaf';
					return $scope.treeData.isLeaf(item);
//						if($scope.treeData.getChilds(item[$scope.valueField].value).length<=0){
//							return true;
//						}else{
//							return false;
//						}
				 };
				 
				 $scope.itemClicked = function(item, $event){
					 //warpCallback('itemClicked', treeData.rows.indexOf(row),row[valueField].value, $event)
					 var rowIndex = $scope.treeData.rows.indexOf(item);
					 var rowID = item[$scope.valueField].value;
					 //触发data的clicked事件
					 $scope.treeData.onRowClick(item, $event)
					 var event = {};
					 event.rowIndex = rowIndex;
					 event.rowID = rowID;
					 //触发用户自定义事件
					 $scope.warpEventCallback('onRowClicked', event);
					 $event.stopPropagation();
				 };
				 
				 $scope.itemDblClicked = function(item, $event){
					 //warpCallback('itemClicked', treeData.rows.indexOf(row),row[valueField].value, $event)
					 var rowIndex = $scope.treeData.rows.indexOf(item);
					 var rowID = item[$scope.valueField].value;
					 //触发data的clicked事件
//						 $scope.treeData.itemExpanded(item,$event)
					 $scope.treeData.onRowDblClick(item,$event)
					 var event = {};
					 event.rowIndex = rowIndex;
					 event.rowID = rowID;
					 //触发用户自定义事件
					 $scope.warpEventCallback('onRowDblClicked', event);
					 $event.stopPropagation();
				 };

				 $scope.warpEventCallback = function(callback, event){
					  ($scope[callback] || angular.noop)({
						  event:event
					 });
				 };
				 
				 //切换
				 $scope.itemExpanded = function(item, $event){
					 var rowIndex = $scope.treeData.rows.indexOf(item);
					 var rowID = item[$scope.valueField].value;
					 /*
						 //挂载子节点数据
						 if($scope.treeData.treeOption.rootFilter!='' && item.$$isMounted!=true){
							 $scope.treeData.mountChildData(rowID,rowIndex);
							 //标记当前行已挂载
							 item.$$isMounted=true;
						 }
//						 console.log('$scope.treeData-->',$scope.treeData);
						 */
					 $scope.treeData.itemExpanded(item,$event);
//						 $scope.warpToggleCallback('itemExpandToggle', item, $event);
					 $event.stopPropagation();
				 };
				 
				 $scope.itemChecked = function(item, $event){
					 $scope.warpToggleCallback('itemCheckedToggle', item, $event);
					 $event.stopPropagation();
				 };
				 
				 $scope.badgeShowFunc = function(row){
					 //console.log('$scope.badgeShow-->',$scope.badgeShow);
					 if($scope.badgeShow=='true'){
						 return true;
					 }else if($scope.badgeShow=='nkLeaf'){
						 if(row.nodeKind.value=='nkLeaf'){
							 return true;
						 }else{
							 return false;
						 }
					 }else if($scope.badgeShow=='noLeaf'){
						 if(row.nodeKind.value==null){
							 return true;
						 }else{
							 return false;
						 }
					 }else if($scope.badgeShow=='level-1'){
						 if(row.nodeLevel.value==1){
							 return true;
						 }else{
							 return false;
						 }
					 }else{
						 return false;
					 }
				 };
				 
				 /*
				  *放到data中去作为标准啦

				 //显示
				 $scope.expand = function(item){
					 var childrens = $scope.getChilds(item);
					 for(var i=0;i<childrens.length;i++){
						 childrens[i].$$isVisible = true;
					 }
				 }
				 
				 //隐藏
				 $scope.collapse = function(item){
					 var childrens = $scope.getChilds(item);
					 for(var i=0;i<childrens.length;i++){
						 childrens[i].$$isVisible = false;
						 //关闭孩子的孩子
						 if(childrens[i].$$isExpand==true){
							 childrens[i].$$isExpand=false;
							 $scope.collapse(childrens[i]);
						 }
					 }
				 }

				 $scope.getChilds = function(item){
					var childrens = [];
					var rows = $scope.treeData.data.rows;
					for(var i=0;i<rows.length;i++){
						var row = rows[i];
						if(row[$scope.parentField].value==item[$scope.valueField].value){
							childrens.push(row);
						}
					}
					return childrens; 
				 };
				 */

				 $scope.warpCallback = function(callback, rowIndex, rowID, $event){
					  ($scope[callback] || angular.noop)({
						 rowIndex:rowIndex,
						 rowID:rowID,
						 $event:$event
					 });
				 };

				 $scope.warpToggleCallback = function(callback, row, $event){
					  ($scope[callback] || angular.noop)({
						 row:row,
						 $event:$event
					 });
				 };
			 }],
			 link:function (scope, element, attrs, controller){
//				scope.number = scope.number + "33333 ";  
//				 
				//设置高度
//				console.log('element-->>',element);
//				console.log('$(window).height()-->>',$(window).height());
//				console.log('scope.subHeight-->>',scope.subHeight);
				if(scope.subHeight){
					//element.find('div').css("height","700px");
					var height = $(window).height() - scope.subHeight;
//					console.log('height-->>',height);
					element.find('div').css("height",height+'px');
				}
				

				/*
				function load(rows){
					for(var i=0;i<rows.length;i++){
						var row = rows[i];
						addLi(row[scope.textField].value);
						if(row.rows){
							load(row.rows);
						}
					}
				}
				var ul = $("<ul class='list-group tree-view' style='border:1px solid #ff0000'>");
				function addLi(text,nodeLevel){
					var li = $("<li class='list-group-item'" + 
							"ng-bind='asdf'" +
							">" +
							text +
							"</li>"
							);	
					li.appendTo(ul);
				}
				*/
				/*
				scope.$watch('treeData',function(newValue,oldValue,scope){
					if(newValue==oldValue){
						return;
					}
					//执行遍历
					var data = scope.treeData;
					if(scope.treeData.length>0){
						ul.appendTo(element);
						load(scope.treeData);
					}

				},true);
				*/
				
			 }
			 /*
				 ,compile: function(element, attributes) {
				    return { 
				        pre: function preLink(scope, element, attributes) {  
				            scope.number = scope.number + "44444 ";  
							scope.$watch('treeData',function(newValue,oldValue,scope){
								//执行遍历
								var data = scope.treeData;
//								load(scope.treeData.data.rows);

							},true);

				        },  
				        post: function postLink(scope, element, attributes) {  
				            scope.number = scope.number + "55555 "; 
							scope.$watch('treeData',function(newValue,oldValue,scope){
								//执行遍历
								var data = scope.treeData;
//								load(scope.treeData.data.rows);

							},true);

							
				        }  
				    };  
				}
				*/
			 
		 };
	 })
	 
});

